package com.yuan.zs.ui.account;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.base.framework.BaseUserManager;
import com.yuan.base.framework.bean.TipResult;
import com.yuan.base.framework.bean.UserInfo;
import com.yuan.base.framework.http.BaseHttpCallBack;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.base.utils.DialogUtil;
import com.yuan.zs.R;
import com.yuan.zs.Urls;
import com.yuan.zs.bean.Grade;
import com.yuan.zs.bean.School;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StringUtils;

/**
 * 申请孩子绑定
 */
public class ApplyChildBindingActivity extends BaseFrameworkActivity {

	private final int REQUEST_SELECT_PHOTO = 1;
	private final int REQUEST_TAKE_PHOTO = 2;

	private EditText et_child_name;
	private EditText et_child_id_card;
	private EditText et_child_relationship;
	private TextView tv_is_main_account;
	private ImageView iv_img1;
	private ImageView iv_img2;

	private TextView tv_child_school;
	private TextView tv_child_grade;

	private List<School> schoolList;
	private List<Grade> gradeList;
	private School selectSchool;
	private Grade selectGrade;
	public int whichImg;
	private String path1;
	private String path2;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_apply_child;
	}

	@Override
	protected void bindViews() {
		iv_img1 = findViewById(R.id.iv_img1);
		iv_img2 = findViewById(R.id.iv_img2);
		et_child_name = findViewById(R.id.et_child_name);
		et_child_id_card = findViewById(R.id.et_child_id_card);
		et_child_relationship = findViewById(R.id.et_child_relationship);
//		tv_is_main_account = findViewById(R.id.tv_is_main_account);
		tv_child_school = findViewById(R.id.tv_child_school);
		tv_child_grade = findViewById(R.id.tv_child_grade);

//		tv_is_main_account.setOnClickListener(v -> selectIsMain());
		tv_child_school.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (schoolList == null) {
					BaseHttpRequest.get(Urls.getUrl(Urls.getAllSchool), new BaseHttpCallBack<JSONObject>() {
						@Override
						public void onPost() {
							hideProgressBar();
						}

						@Override
						public void onPreStart() {
							showProgressBar("正在加载数据");
						}

						@Override
						public void onSuccess(JSONObject result) {
							schoolList = JSON.parseArray(result.getString("content"), School.class);
							showSelectSchool(schoolList);
						}
					});
				} else {
					showSelectSchool(schoolList);
				}
			}
		});
		tv_child_grade.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (selectSchool == null) {
					showToast("请先选择学校");
					return;
				}
				if (gradeList == null) {
					HashMap<String, Object> params = new HashMap<>();
					params.put("school", selectSchool.getId());
					BaseHttpRequest.get(Urls.getUrl(Urls.getGradeById), params, new BaseHttpCallBack<JSONObject>() {
						@Override
						public void onPost() {
							hideProgressBar();
						}

						@Override
						public void onPreStart() {
							showProgressBar("正在加载数据");
						}

						@Override
						public void onSuccess(JSONObject result) {
							gradeList = JSON.parseArray(result.getString("content"), Grade.class);
							showSelectClass(gradeList);
						}
					});
				} else {
					showSelectClass(gradeList);
				}
			}
		});
		setOnClickListener(R.id.btn_submit, v -> doSubmit());
		iv_img1.setOnClickListener(v -> {
			whichImg = 1;
			takePhoto();
		});
		iv_img2.setOnClickListener(v -> {
			whichImg = 2;
			takePhoto();
		});
	}

	private void takePhoto() {
		String[] items = {"拍照", "从相册中选择"};
		DialogUtil.select(this, "请选择图片来源", items, (dialog, which) -> {
			switch (which) {
				case 0:
					// 拍照
					GalleryFinal.openCamera(REQUEST_SELECT_PHOTO, new FunctionConfig.Builder().build(), onHanlderResultCallback);
					break;
				case 1:
					// 本地选取
					GalleryFinal.openGallerySingle(REQUEST_SELECT_PHOTO, new FunctionConfig.Builder().build(), onHanlderResultCallback);
					break;
			}
		}, "取消", null);
	}

	private GalleryFinal.OnHanlderResultCallback onHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {

		@Override
		public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
			switch (reqeustCode) {
				case REQUEST_SELECT_PHOTO:
				case REQUEST_TAKE_PHOTO:
					upImg(resultList.get(0).getPhotoPath());
					break;
			}
		}

		@Override
		public void onHanlderFailure(int requestCode, String errorMsg) {
//			showToast("图片选择出错");
		}
	};

	private void upImg(String filePath) {
		submitImage(filePath, this, result -> {
			if (whichImg == 1) {
				path1 = result;
				iv_img1.setImageURI(Uri.parse(filePath));
			} else if (whichImg == 2) {
				path2 = result;
				iv_img2.setImageURI(Uri.parse(filePath));
			}
		});
	}

	private ProgressDialog mProgressDialog;

	public void submitImage(final String path, final BaseFrameworkActivity activity, final UploadSuccess onSuccess) {
		File file = new File(path);
		BaseHttpRequest.post(Urls.getUrl(Urls.upload), file, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onLoading(long current, long total) {
				mProgressDialog.setProgress((int) (((float) current / (float) total) * 100));
			}

			@Override
			public void onPreStart() {
				mProgressDialog = new ProgressDialog(activity);
				mProgressDialog.setTitle("正在上传...");
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				mProgressDialog.setMax(100);
				mProgressDialog.setCanceledOnTouchOutside(false);
				mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
					if (getCancelable() != null) {
						getCancelable().cancel();
					}
				});
				mProgressDialog.show();
			}

			@Override
			public void onSuccess(TipResult result) {
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
				if (StringUtils.isEmpty(result.getMessage())) {
					activity.showToast("上传失败,请重试");
				} else {
					onSuccess.onSuccess(result.getMessage());
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				activity.showToast("上传失败,请重试");
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
			}

			@Override
			public void onPost() {
				mProgressDialog = null;
			}
		});
	}

	public interface UploadSuccess {
		void onSuccess(String fileId);
	}

	private void showSelectSchool(List<School> schoolList) {
		String[] schools = new String[schoolList.size()];
		for (int i = 0; i < schoolList.size(); i++) {
			schools[i] = schoolList.get(i).getName();
		}
		DialogUtil.select(this, "选择学校", schools, (dialog, which) -> {
			tv_child_school.setText(schools[which]);
			selectSchool = schoolList.get(which);
			gradeList = null;
			tv_child_grade.setText("");
			selectGrade = null;
		});
	}

	private void showSelectClass(List<Grade> gradeList) {
		String[] schools = new String[gradeList.size()];
		for (int i = 0; i < gradeList.size(); i++) {
			schools[i] = gradeList.get(i).getName();
		}
		DialogUtil.select(this, "选择班级", schools, (dialog, which) -> {
			tv_child_grade.setText(schools[which]);
			selectGrade = gradeList.get(which);
		});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	private void selectIsMain() {
		String[] sex = new String[]{"是", "否"};
		DialogUtil.select(this, "选择是否主账号", sex, (dialog, which) -> tv_is_main_account.setText(sex[which]));
	}

	private void doSubmit() {
		if (TextUtils.isEmpty(getStringTrimByUI(et_child_name))) {
			showToast("请填写幼儿姓名");
			return;
		}
		if (TextUtils.isEmpty(getStringTrimByUI(et_child_id_card))) {
			showToast("请填写幼儿身份证");
			return;
		}
		if (TextUtils.isEmpty(getStringTrimByUI(et_child_relationship))) {
			showToast("请填写与幼儿关系");
			return;
		}
		if (TextUtils.isEmpty(getStringTrimByUI(tv_child_school))) {
			showToast("请选择学校");
			return;
		}
		if (TextUtils.isEmpty(getStringTrimByUI(tv_child_grade))) {
			showToast("请选择班级");
			return;
		}
		UserInfo user = BaseUserManager.getUser();
		HashMap<String, Object> params = new HashMap<>();
//		params.put("name", user.getName());
//		params.put("idCardNo", user.getIdCardNo());
//		params.put("gender", user.getGender());
//		params.put("phone1", PreferencesUtils.getString(this, Constant.Preferences.USER_CODE, ""));

		params.put("childName", getStringTrimByUI(et_child_name));
		params.put("childIdCardNo", getStringTrimByUI(et_child_id_card));
		params.put("relationship", getStringTrimByUI(et_child_relationship));
//		params.put("principal", getStringTrimByUI(tv_is_main_account).equals("是"));

		params.put("schoolId", selectSchool.getId() + "");
		params.put("classId", selectGrade.getId() + "");
		params.put("pic1", path1);
		params.put("pic2", path2);
		BaseHttpRequest.post(Urls.getUrl(Urls.applyChildBinding), params, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onPost() {
				hideProgressBarAtOnce();
			}

			@Override
			public void onPreStart() {
				showProgressBar("正在提交...");
			}

			@Override
			public void onSuccess(TipResult result) {
				if (result.isSuccess()) {
					showToast("申请成功，请等待审核");
					closeSelf();
				} else {
					showToast(result.getMessage());
				}
			}
		});
	}


}
